using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using MvcShop.Models;
using MvcShop.Models.Repositories;
using xVal.ServerSide;
using MvcShop.Models.ViewDataModels;
using System.ComponentModel;

namespace MvcShop.MVC.Areas.Admin.Controllers
{
    public class NewsManageController : Controller
    {
        //
        // GET: /NewsManage/
        #region ==== Fields ====
        private INewsRepository<News> _newsRepository;
        private NewsViewData _newsViewData;
        private const int pageSize = 40;
        #endregion

        #region ==== Constructors ====
        public NewsManageController(INewsRepository<News> newsRepository)
        {
            this._newsRepository = newsRepository;
            this._newsViewData = NewsView.Data;
        }
        #endregion

        public ActionResult ManageNews(int? page)
        {
            var criteria = new NotEqualCriteria("NewsId", 0);
            Order orderExpr = new Order(OrderType.ASC, "NewsId");

            this.NewsData.WithPageIndex((page == null) ? 1 : Convert.ToInt32(page));
            this.NewsData.WithCount(this._newsRepository.Count(criteria));
            this.NewsData.WithTotal(pageSize);

            this.NewsData.WithNewsList(this._newsRepository.FindAll(this.NewsData.PageIndex,pageSize));
            return View(this.NewsData);
        }

        public ActionResult NManageNews()
        {
            return View();
        }

        [HttpPost]
        public ActionResult GetNewsList([DefaultValue(1)]int page, [DefaultValue(20)]int rp,
            [DefaultValue("NewsId")]string sortname, [DefaultValue("desc")]string sortorder,
            [DefaultValue(null)]string query, [DefaultValue("Title")]string qtype)
        {
            OrderType orderType = OrderType.DESC;
            if (sortorder == "asc") orderType = OrderType.ASC;

            ICriteria criteria = new NotEqualCriteria("NewsId", 0);
            if (!string.IsNullOrEmpty(query))
            {
                if (qtype == "NewsId")
                {
                    int temp;
                    if (int.TryParse(query, out temp))
                        criteria = new EqualCriteria(qtype, temp);
                }
                else
                {
                    criteria = new LikeCriteria(qtype, query);
                }
            }

            Order orderExpr = new Order(orderType, sortname);
            int pCount = this._newsRepository.Count(criteria);

            var products = this._newsRepository.Find(criteria, page, rp, orderExpr);
            var nl = from n in products
                     select new Rows { id = n.NewsId, cell = new object[] { n.NewsId, n.Title, n.HeadLine, n.HighLight, n.DateTime.ToString() } };

            return Json(new { total = pCount, page = page, rows = nl });
        }


        public ActionResult AddNews()
        {
            var news = new News { Title = "IT" };
            return View("Edit", news);
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult AddNews([Bind(Exclude="NewsId")]News news)
        {
            news.DateTime = DateTime.Now;
            var errors = DataAnnotationsValidationRunner.GetErrors(news);
            if (errors.Any())
            {
                new RulesException(errors).AddModelStateErrors(ModelState, "news");
                return View("Edit", news);
            }

            this._newsRepository.Add(news);
            this._newsRepository.SaveChanges();
            return RedirectToAction("NManageNews");
        }

        public ActionResult Edit(int id)
        {
            var news = this._newsRepository.Find(id);
            return View(news);
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(News news)
        {
            news.DateTime = DateTime.Now;
            var errors = DataAnnotationsValidationRunner.GetErrors(news);
            if (errors.Any())
            {
                new RulesException(errors).AddModelStateErrors(ModelState, "news");
                return View("Edit", news);
            }

            this._newsRepository.Update(news.NewsId, news);
            this._newsRepository.SaveChanges();
            return RedirectToAction("NManageNews");
        }

        public ActionResult Delete(int id)
        {
            this._newsRepository.Del(this._newsRepository.Find(id));
            this._newsRepository.SaveChanges();
            return RedirectToAction("ManageNews");
        }

        public ActionResult Del(string newsId)
        {
            var caid = StringExtensions.ConvertIntList(newsId);
            this._newsRepository.Del(caid);

            return RedirectToAction("NManageNews");
        }

        public NewsViewData NewsData { get { return this._newsViewData; } }
    }
}
